package com.siyoumi.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.SysAddress;
import com.siyoumi.app.mapper.SysAddressMapper;
import com.siyoumi.entity.EntityBase;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.util.XReturn;
import com.siyoumi.component.XSpringContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

//t_s_address
@Service
public class SysAddressService
        extends ServiceImplBase<SysAddressMapper, SysAddress> {
    static public SysAddressService getBean() {
        return XSpringContext.getBean(SysAddressService.class);
    }

    /**
     * 获取默认地址
     */
    public SysAddress getDef(String openid) {
        QueryWrapper<SysAddress> query = q()
                .eq("addr_openid", openid)
                .eq("addr_def", 1);
        return first(query);
    }

    /**
     * 设置默认地址
     */
    @Transactional(propagation = Propagation.MANDATORY)
    public void setDef(SysAddress entity) {
        //旧默认地址还原
        QueryWrapper<SysAddress> query = q()
                .eq("addr_openid", entity.getAddr_openid())
                .eq("addr_def", 1)
                .ne(fdKey(), entity.getKey());
        List<SysAddress> list = mapper().selectList(query);
        if (list.size() > 0) {
            List<String> ids = list.stream().map(EntityBase::getKey).collect(Collectors.toList());
            update().in(fdKey(), ids)
                    .set("addr_def", 0)
                    .update();
        }

        //标记新的
        update().eq(fdKey(), entity.getKey())
                .set("addr_def", 1)
                .update();
    }

    private final static Pattern patternPc = Pattern.compile(".+?(省|市|自治区|自治州|县|区)");

    /**
     * 获取地址，省市部分
     */
    public XReturn getAddressPc(String address) {
        Matcher matcher = patternPc.matcher(address);
        List<String> arr = new ArrayList<>();
        while (matcher.find()) {
            arr.add(matcher.group());
        }
        if (arr.size() <= 0) {
            return XReturn.getR(20068, "地址异常");
        }

        XReturn r = XReturn.getR(0);
        r.setData("province", arr.get(0));
        if (arr.size() > 1) {
            r.setData("city", arr.get(1));
        }

        return r;
    }
}
